/*
 * Adara WebCam TimeLapse capture software.
 * Copyright (C) 2012 AdaraProjectTeam
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package adara.core.process;

import java.io.File;
import java.util.Collection;
import java.util.Observable;

import org.apache.log4j.Logger;

import adara.core.CoreRuntimeException;
import adara.core.Device;
import adara.plugins.Plugin;
import adara.plugins.PluginManager;

import com.lti.civil.CaptureException;
import com.lti.civil.CaptureObserver;
import com.lti.civil.CaptureStream;
import com.lti.civil.Image;
import com.lti.civil.awt.AWTImageConverter;

/**
 * This class implements the functionality of getting the images from attached
 * device and delivery them to plugins for processing.
 * @author Andrei Ermicioi (aka erani) <andrei.ermicioi@gmail.com>
 *
 */
public abstract class Process extends Observable implements Runnable, CaptureObserver {
	
	private static final Logger logger = Logger.getLogger(Process.class);
	
	private Device device;
	private int timegap;
	private File storage;
	private CaptureStream stream;
	
	private Collection<Plugin> plugins;
	
	private long nextTime = -1;
	private boolean isAlive;
	
	public Process(Device device, int timegap, File storage, CaptureStream stream) {
		this.device = device;
		this.timegap = timegap;
		this.storage = storage;
		this.stream = stream;
		
		this.stream.setObserver(this);
		
		plugins = PluginManager.getPlugins();
	}
	
	/**
	 * Returns in precentage the progress status.
	 * @return
	 */
	public abstract int getProgressStatus();
	
	/**
	 * Says if the process should stop.
	 * @return
	 */
	protected abstract boolean shouldStop();
	
	@Override
	public void run() {
		if (device.isLocked()) {
			throw new CoreRuntimeException("Device is locked");
		}
		
		this.lockDevice();
		
		for (Plugin plugin : plugins) {
			plugin.init(timegap, storage);
			this.addObserver(plugin);
		}
		
		this.startStream();
		
		while (isAlive) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) { }
			
			isAlive = !this.shouldStop();
		}
		
		for (Plugin plugin : plugins) {
			plugin.close();
		}
		
		this.stopStream();
		this.unlockDevice();
	}
	
	@Override
	public void onError(CaptureStream stream, CaptureException e) {
		logger.error("Error on capturing image", e);
	}

	@Override
	public void onNewImage(CaptureStream stream, Image image) {
		long imgTimestamp = image.getTimestamp() / 1000;
		
		if (nextTime == -1) {
			nextTime = imgTimestamp + Process.this.timegap;
			
			if (logger.isTraceEnabled())
				logger.trace("Next snapshot at: " + nextTime);
			
			return;
		}
		
		if (nextTime > imgTimestamp) {
			return;
		}
		
		setChanged();
		notifyObservers(AWTImageConverter.toBufferedImage(image));
		
		nextTime += Process.this.timegap;
		
		if (logger.isTraceEnabled())
			logger.trace("Next snapshot at: " + nextTime);
	}
	
	/**
	 * Launch the process
	 */
	protected void launch() {
		isAlive = true;
		new Thread(this).start();
	}
	
	/**
	 * Locks the device, to not be used by other process.
	 */
	private synchronized void lockDevice() {
		if (device.isLocked()) {
			throw new CoreRuntimeException("Device is locked");
		}
		
		if (logger.isTraceEnabled()) {
			logger.trace("Locking device");
		}
		
		device.lock();
	}
	
	/**
	 * Unlock the device, to be able to used by other process.
	 */
	private void unlockDevice() {
		if (logger.isTraceEnabled()) 
			logger.trace("Device unlocked");
		
		device.unlock();
	}
	
	/**
	 * Start the device stream
	 */
	private void startStream() {
		try {
			if (logger.isTraceEnabled())
				logger.trace("Starting stream");
			
			stream.start();
		} catch (CaptureException e) {
			throw new CoreRuntimeException(e);
		}
	}
	
	/**
	 * Stop the device stream
	 */
	private void stopStream() {
		try {
			if (logger.isTraceEnabled())
				logger.trace("Stoping stream");
			
			stream.stop();
		} catch (CaptureException e) {
			throw new CoreRuntimeException(e);
		}
		
		try {
			if (logger.isTraceEnabled())
				logger.trace("Disposing stream");
			
			stream.dispose();
		} catch (CaptureException e) {
			throw new CoreRuntimeException(e);
		}
	}
}
